package com.example.xss.commom.validation;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.EnumUtil;
import com.example.xss.commom.enums.IBaseEnum;
import com.example.xss.commom.validation.annotation.EnumValueCheck;
import org.hibernate.validator.internal.engine.constraintvalidation.ConstraintValidatorContextImpl;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.Arrays;
import java.util.List;

/**
 * $
 *
 * @author WANGJIET24
 * @date 2021-6-9$
 */
public class EnumValueValidator implements ConstraintValidator<EnumValueCheck, Object> {
    private Class<?> enumClass;

    @Override
    public void initialize(EnumValueCheck constraintAnnotation) {
        enumClass = constraintAnnotation.enumClass();
    }

    @Override
    public boolean isValid(Object o, ConstraintValidatorContext constraintValidatorContext) {
        // 枚举校验
        if (EnumUtil.isEnum(o.getClass())) {
            if (!Arrays.asList(o.getClass().getInterfaces()).contains(IBaseEnum.class)) {
                throw new IllegalArgumentException("校验错误，当前校验枚举需要继承IBaseEnum");
            }
            // 得到枚举值
            List<Object> enumValueList = CollUtil.newArrayList();
            for (Object enumConstant : o.getClass().getEnumConstants()) {
                IBaseEnum<?, ?> constant = (IBaseEnum<?, ?>) enumConstant;
                if (!"-1".equals(constant.getValue().toString())) {
                    enumValueList.add(constant.getValue());
                }
            }
            ConstraintValidatorContextImpl context = (ConstraintValidatorContextImpl) constraintValidatorContext;
            IBaseEnum<?, ?> constant = (IBaseEnum<?, ?>) o;
            context.addExpressionVariable("hahf", "hdhf");
            if (!enumValueList.contains(constant.getValue())) {
                String stringBuffer = "枚举值校验失败，只能是【" +
                        CollUtil.join(enumValueList, ",");
//                constraintValidatorContext.buildConstraintViolationWithTemplate(stringBuffer);
                constraintValidatorContext.buildConstraintViolationWithTemplate("hahaha");
                return false;
            }

        } else {
            // 普通参数校验，同时没有指定枚举
            if (null == enumClass) {
                throw new IllegalArgumentException("请指定枚举信息：EnumValueCheck.enumClass");
            }

        }

        return true;
    }
}
